package com.yexiao.cofe.business.controller;

import com.yexiao.cofe.util.FileUtil;
import com.yexiao.core.response.ResponseData;
import com.yexiao.core.util.JSONUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author lkl
 * @since 2025/4/8
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileUtil fileUtil;

    @PostMapping("/upload")
    public ResponseData upload(@RequestParam("file") MultipartFile file) {
        try {
            // 生成唯一文件名（避免覆盖）
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path targetLocation = fileUtil.getFileStorageLocation().resolve(fileName);

            // 保存文件
            Files.copy(file.getInputStream(), targetLocation);

            // 生成文件访问URL
            String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/files/")      // 匹配静态资源映射路径
                    .path(fileName)
                    .toUriString();

            return ResponseData.success(JSONUtil.of("url", fileUrl));
        } catch (IOException ex) {
            throw new RuntimeException("文件上传失败！", ex);
        }
    }


}
